<?php
namespace app\admin\controller\setting;

use app\admin\controller\Base;
use app\admin\model\Role as ModelRole;
use Atlaxy\Node;

/**
 * 角色列表
 */
class Role extends Base
{
    /**
     * 角色列表
     * @auth true
     */
    public function index()
    {
        $this->list = ModelRole::like('name')->order('id','desc')->paginate(20);
        $this->fetch();
    }

    /**
     * 添加角色
     * @auth true
     */
    public function add()
    {
        if($this->request->isGet()){
            $this->fetch('edit');
        }else{
            $name = $this->request->post('name',null,'trim');
            if(!$name)$this->jsonFail('请输入角色名称');
            $has = ModelRole::where('name', $name)->find();
            if($has){
                $this->jsonFail('角色已存在！');
            }else{
                $res = ModelRole::create(compact('name'));
                if($res)$this->jsonSucc();
                else $this->jsonFail("添加失败！");
            }
        }
    }

    /**
     * 编辑角色
     * @auth true
     */
    public function edit()
    {
        if($this->request->isGet()){
            $this->model = ModelRole::find($this->request->get('id'));
            return $this->fetch();
        }else{
            $id = $this->request->post('id');
            $name = $this->request->post('name',null,'trim');
            if(!$name)$this->jsonFail('请输入角色名称');

            $model = ModelRole::find($id);
            $model->name = $name;
            if($model->save())$this->jsonSucc();
            else $this->jsonFail("修改失败！");
        }
    }

    /**
     * 删除角色
     * @auth true
     */
    public function delete()
    {
        $id = $this->request->post('id');
        $model = ModelRole::find($id);
        if($id == 10000)$this->jsonFail('超级管理员不可删除！');
        if($model->delete())$this->jsonSucc();
        else $this->jsonFail("删除失败！");
    }

    public function auth()
    {
        $id = $this->request->get('id');
        $role = ModelRole::find($id);
        if(!$role) $this->jsonFail("角色不存在");
        if($this->request->isGet()){
            $this->nodes = Node::instance()->getTree(explode(',',$role->urls));
            $this->fetch();
        }else{
            $urls = $this->request->post('urls');
            $role->urls = implode(',',$urls);
            if($role->save()) $this->jsonSucc();
            else $this->jsonFail("操作失败");
        }
    }
}